var markdownEditor;
var wangEditor;
var flag = 1
layui.use(['form', 'layedit', 'laydate'], function() {
	form = layui.form, layer = layui.layer, layedit = layui.layedit,upload = layui.upload;
	//自定义验证规则
	form.verify({
		title: function(value) {
			if(value.length < 5) {
				return '标题至少得5个字符啊';
			}
		}
	});

 //普通图片上传
  var uploadInst = upload.render({
    elem: '#cover'
    ,url: '/upload/'
    ,before: function(obj){
      //预读本地文件示例，不支持ie8
      obj.preview(function(index, file, result){
        $('#coverUrl').attr('src', result); //图片链接（base64）
      });
    }
    ,done: function(res){
      //如果上传失败
      if(res.code > 0){
        return layer.msg('上传失败');
      }
      //上传成功
    }
    
  });

	//监听指定开关
	form.on('switch(switchTest)', function(data) {
		layer.msg('开关checked：' + (this.checked ? 'true' : 'false'), {
			offset: '6px'
		});
		layer.tips('温馨提示：请注意开关状态的文字可以随意定义，而不仅仅是ON|OFF', data.othis)
	});

	//监听提交
	form.on('submit(demo1)', function(data) {
		flag = flag + 1;
		var editor = $(".editor").val() //获取所使用编辑器
		console.log(decodeURIComponent(encodeURIComponent(wangEditor.txt.html())))
		if(data.field.editor == "markdown") {
			data.field.content = markdownEditor.getMarkdown();
		} else if(data.field.editor == "html") {
			data.field.content = encodeURIComponent(wangEditor.txt.html());
		} else {
			data.field.content = "-1";
		}
		layer.alert(JSON.stringify(data.field), {
			title: '最终的提交信息'
		})
		return false;
	});

	//表单初始赋值
	form.val('example', {
		"title": "MySQL安装教程",
		"music": "3",
		"articleType": 1,
		"like[write]": true,
		"close": true,
		"cover": function() {
			$("#cover").attr("src", "/images/banner_bg_1.jpg")
			$(".cover").val("/images/banner_bg_1.jpg")
		},
		"isOriginal": "转载",
		"content": "",
		"editor": "markdown"

	})

	/*选择使用那个编辑器*/
	form.on('radio(editor)', function(data) {
		if(data.value == "html") {
			$("#editormd").hide()
			$("#html-editor").show()
		} else {
			$("#html-editor").hide()
			$("#editormd").show()
		}
	});

	$("#checkMusic").click(function() {
		layer.open({
			type: 2,
			title: '我的音乐',
			area: ['500px', '300px'],
			shade: 0.3,
			maxmin: true,
			content: '/zhl/music_check.html',
			btn: ['确定', '关闭'], //只是为了演示
			yes: function(obj) {
				var id = "layui-layer-iframe" + flag;
				var doc;
				if(document.all) { // IE 
					doc = document.frames[id].document;
				} else { // 标准
					doc = document.getElementById(id).contentDocument;
				}
				var musicId = doc.getElementById("musicId").textContent;
				if(musicId == undefined || musicId == "") {
					doc.getElementById("musicId").click()
				} else {
					var str = musicId.split(",")
					$("#checkMusic").text(str[1])
					$("#music_id").val(str[0])
					layer.closeAll();
				}
				flag = flag + 1;
			},
			btn2: function() {
				layer.closeAll();
			},
			zIndex: layer.zIndex //重点1
				,
			success: function(layero) {
				layer.setTop(layero); //重点2
			}

		})

	})
});

/*侧边栏*/
$(function() {
	$(".site-tree-mobile").click(function() {
		$("body").addClass("site-mobile");
		$(".site-mobile-shade").click(function() {
			$("body").removeClass("site-mobile");
		});
	});
});

/*第一次加载页面隐藏html编辑器*/
$(function() {
	$("#html-editor").hide()
})

/*初始化wangeditor*/
var E = window.wangEditor
wangEditor = new E('#div3')
wangEditor.customConfig.uploadImgServer = '/api/file'
wangEditor.create()

/*初始化markdown*/
$(function() {
	markdownEditor = editormd("editormd", {
		width: "90%",
		height: 540,
		path: '/editormd/lib/',
		watch: false, // 关闭实时预览
		//toolbar  : false,             //关闭工具栏
		//previewCodeHighlight : false, // 关闭预览 HTML 的代码块高亮，默认开启
		//emoji: true,
		taskList: true,
		tocm: true, // Using [TOCM]
		tex: true, // 开启科学公式TeX语言支持，默认关闭
		flowChart: true, // 开启流程图支持，默认关闭
		sequenceDiagram: true, // 开启时序/序列图支持，默认关闭,
		imageUpload: true,
		imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
		imageUploadURL: "/api/file",
		onload: function() {
			console.log('onload', this);
			//this.fullscreen();
			//this.unwatch();
			//this.watch().fullscreen();

			//this.setMarkdown("#PHP");
			//this.width("100%");
			//this.height(480);
			//this.resize("100%", 640);
		}
	});
});